package com.ztorn.config;

import com.ztorn.security.*;
import com.ztorn.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true) // 启用方法级别的安全性（如@PreAuthorize、@PostAuthorize等）
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // 使用BCryptPasswordEncoder加密密码
//        PasswordEncoder encoder = new BCryptPasswordEncoder();
        auth.userDetailsService(userDetailsService()).passwordEncoder(passwordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .cors() // 如果需要跨域支持，可以启用CORS
                .and()
                .csrf().disable() // 关闭CSRF防护，因为JWT不需要CSRF令牌
                .authorizeRequests()
                .antMatchers("/api/login").permitAll()
                .antMatchers("/api/register").permitAll()// 允许未经身份验证的用户访问登录、注册等接口
                    .anyRequest().authenticated() // 其他所有请求都需要身份验证
                .and()
                .exceptionHandling()
                    .accessDeniedHandler(new JwtAccessDeniedHandler()) // 自定义访问拒绝处理器
                    .authenticationEntryPoint(new JwtAuthenticationEntryPoint()) // 自定义未授权处理器
                .and()
                .sessionManagement()
                    .sessionCreationPolicy(SessionCreationPolicy.STATELESS) // 使用无状态会话，适用于JWT
                .and()
                .addFilterBefore(new JwtAuthorizationFilter(userDetailsService,jwtUtils), UsernamePasswordAuthenticationFilter.class)
                .addFilter(new JwtAuthenticationFilter(authenticationManagerBean(),jwtUtils)); // 注册JwtAuthenticationFilter
    }

    @Bean
    public UserDetailsService userDetailsService() {
        return new JwtUserDetailsService(); // 返回自定义的UserDetailsService实现
    }


    // 可选：如果需要自定义访问拒绝处理器和未授权处理器
    @Bean
    public JwtAccessDeniedHandler jwtAccessDeniedHandler() {
        return new JwtAccessDeniedHandler();
    }

    @Bean
    public JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint() {
        return new JwtAuthenticationEntryPoint();
    }


    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
